﻿//文件指定编译编码UTF-8
#pragma execution_character_set("utf-8")

/**
*    @file:    spectrumplaybackwebsocketclient.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2025-04-01  11:46
*/

#include "spectrumplaybackwebsocketclient.h"

#include <QFile>
#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonObject>
#include <QThread>
#include <qglobalconfig.h>


SpectrumPlaybackWebSocketClient::SpectrumPlaybackWebSocketClient(QWebSocket *socket,QObject *parent):QObject(parent)
{
    pSocket = socket;
    qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");
//    pSocket->setParent(this);
    connect(pSocket,&QWebSocket::textMessageReceived,this,&SpectrumPlaybackWebSocketClient::slot_recvTextMessage);
    connect(pSocket, &QWebSocket::disconnected, this, &QObject::deleteLater);

    spectrumPlayback = new SpectrumPlayback();
    connect(this,&SpectrumPlaybackWebSocketClient::signal_playback,spectrumPlayback,&SpectrumPlayback::playback);
    connect(spectrumPlayback,&SpectrumPlayback::signal_playbackIsRun,this,&SpectrumPlaybackWebSocketClient::slot_playbackIsRun);
    connect(spectrumPlayback,&SpectrumPlayback::signal_playbackMessage,this,&SpectrumPlaybackWebSocketClient::slot_playbackMessage);
    connect(spectrumPlayback,&SpectrumPlayback::signal_playbackSpectrumData,this,&SpectrumPlaybackWebSocketClient::slot_playbackSpectrumData);
    spectrumPlaybackThread = new QThread();
    spectrumPlayback->moveToThread(spectrumPlaybackThread);
    spectrumPlaybackThread->start();

}

SpectrumPlaybackWebSocketClient::~SpectrumPlaybackWebSocketClient()
{
    spectrumPlayback->stop();
    spectrumPlaybackThread->quit();
    spectrumPlaybackThread->wait();
    spectrumPlaybackThread->deleteLater();
    spectrumPlayback->deleteLater();
    qDebug() << "WebSocketWorker destroyed in thread:" << QThread::currentThreadId();
}

void SpectrumPlaybackWebSocketClient::slot_recvTextMessage(QString message)
{
    qDebug() << QString("[%1]: message:%2").arg(__FUNCTION__).arg(message);
    if(message == "@heart"){
        pSocket->sendTextMessage(message);
        return;
    }

    // 解析JSON对象
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError) {
        pSocket->sendTextMessage(QString("JSON parse error : %1").arg(jsonError.errorString()));
        return;
    }

    if (!doc.isObject()) {
        qDebug() << "Received message is not a JSON object";
        return;
    }

    QJsonObject jsonObj = doc.object();
    QString messageType = jsonObj.value("messageType").toString();

    if("fileUrl" == messageType)
    {
        if(!jsonObj.value("url").toString().isEmpty())
            spectrumPlayback->setFileUrl(jsonObj.value("url").toString());
    }
    else if("config" == messageType)
    {
        if(jsonObj.contains("fftLen"))
            spectrumPlayback->setFftLen(jsonObj.value("fftLen").toInt());
        if(jsonObj.contains("winType"))
            spectrumPlayback->setWinType(jsonObj.value("winType").toInt());
        if(jsonObj.contains("dataType"))
            spectrumPlayback->setDataType(jsonObj.value("dataType").toInt());
        if(jsonObj.contains("smooth"))
            spectrumPlayback->setSmooth(jsonObj.value("smooth").toBool());
        if(jsonObj.contains("smoothNum"))
            spectrumPlayback->setSmoothNum(jsonObj.value("smoothNum").toInt());
        if(jsonObj.contains("interval"))
            spectrumPlayback->setInterval(jsonObj.value("interval").toInt());
    }
    else if("start" == messageType)
    {        
        if(!spectrumPlayback->getIsRun()){
           signal_playback();
        }
    }
    else if("stop" == messageType)
    {
        if(spectrumPlayback->getIsRun()){
           spectrumPlayback->stop();
        }
    }
    else
    {
        pSocket->sendTextMessage(QString("Undefined message type : %1").arg(messageType));
    }
}

void SpectrumPlaybackWebSocketClient::slot_playbackMessage(QString message)
{
    QJsonObject object;
    object["messageType"] = "message";
    object["message"] = message;
    pSocket->sendTextMessage(QJsonDocument(object).toJson());
}

void SpectrumPlaybackWebSocketClient::slot_playbackSpectrumData(QString data)
{
//    qDebug()<< __FUNCTION__;
    pSocket->sendTextMessage(QString("{\"messageType\":\"spectrumData\",\"data\":%1}").arg(data));
}

void SpectrumPlaybackWebSocketClient::slot_playbackIsRun(bool isRun)
{
    QJsonObject object;
    object["messageType"] = "status";
    object["status"] = isRun;
    pSocket->sendTextMessage(QJsonDocument(object).toJson());
}
